<template>
    <div class="bg-white p-4 rounded-lg shadow">
        <!-- 操作按钮区域 -->
        <div class="mb-4 flex items-center justify-between">
            <div class="flex items-center space-x-4">
                <el-button type="primary" @click="handleAdd">
                    <el-icon>
                        <Plus />
                    </el-icon>新增菜单
                </el-button>
                <el-button @click="handleExpandAll">
                    <el-icon>
                        <Operation />
                    </el-icon>展开/折叠
                </el-button>
            </div>
        </div>

        <!-- 表格区域 -->
        <el-table :data="tableData" row-key="id" border
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" v-loading="loading">
            <el-table-column prop="title" label="菜单名称" />
            <el-table-column prop="icon" label="图标" width="80">
                <template #default="{ row }">
                    <el-icon v-if="row.icon">
                        <component :is="row.icon" />
                    </el-icon>
                </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="80" />
            <el-table-column prop="path" label="路由地址" />
            <el-table-column prop="component" label="组件路径" />
            <el-table-column prop="permission" label="权限标识" />
            <el-table-column prop="type" label="菜单类型" width="100">
                <template #default="{ row }">
                    <el-tag :type="row.type === '0' ? '' : row.type === '1' ? 'success' : 'info'">
                        {{ row.type === '0' ? '目录' : row.type === '1' ? '菜单' : '按钮' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80">
                <template #default="{ row }">
                    <el-tag :type="row.status === '1' ? 'success' : 'danger'">
                        {{ row.status === '1' ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" @click="handleAdd(row)">新增</el-button>
                    <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
                    <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 菜单表单对话框 -->
        <el-dialog v-model="dialogVisible" :title="formType === 'add' ? '新增菜单' : '编辑菜单'" width="600px">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="上级菜单">
                    <el-tree-select v-model="form.parentId" :data="menuOptions" :props="{ label: 'title', value: 'id' }"
                        placeholder="请选择上级菜单" class="w-full" clearable />
                </el-form-item>
                <el-form-item label="菜单类型" prop="type">
                    <el-radio-group v-model="form.type">
                        <el-radio-button value="0">目录</el-radio-button>
                        <el-radio-button value="1">菜单</el-radio-button>
                        <el-radio-button value="2">按钮</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="菜单名称" prop="title">
                    <el-input v-model="form.title" placeholder="请输入菜单名称" />
                </el-form-item>
                <el-form-item label="图标" prop="icon" v-if="form.type !== '2'">
                    <el-input v-model="form.icon" placeholder="请选择图标">
                        <template #append>
                            <el-button @click="showIconSelect">
                                <el-icon><Select /></el-icon>
                            </el-button>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="路由地址" prop="path" v-if="form.type !== '2'">
                    <el-input v-model="form.path" placeholder="请输入路由地址" />
                </el-form-item>
                <el-form-item label="组件路径" prop="component" v-if="form.type === '1'">
                    <el-input v-model="form.component" placeholder="请输入组件路径" />
                </el-form-item>
                <el-form-item label="权限标识" prop="permission" v-if="form.type !== '0'">
                    <el-input v-model="form.permission" placeholder="请输入权限标识" />
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="form.sort" :min="0" :max="999" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-switch v-model="form.status" :active-value="'1'" :inactive-value="'0'" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Plus, Operation, Select } from '@element-plus/icons-vue'

// 表格数据
const loading = ref(false)
const tableData = ref([])
const isExpandAll = ref(false)

// 表单相关
const dialogVisible = ref(false)
const formType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const form = reactive({
    id: '',
    parentId: '',
    type: '0',
    title: '',
    icon: '',
    path: '',
    component: '',
    permission: '',
    sort: 0,
    status: '1'
})

// 菜单选项
const menuOptions = ref([])

// 表单校验规则
const rules = reactive<FormRules>({
    type: [
        { required: true, message: '请选择菜单类型', trigger: 'change' }
    ],
    title: [
        { required: true, message: '请输入菜单名称', trigger: 'blur' }
    ],
    path: [
        { required: true, message: '请输入路由地址', trigger: 'blur' }
    ]
})

// 根据菜单类型显示不同的校验规则
const dynamicRules = computed(() => {
    const baseRules = { ...rules }
    if (form.type === '1') {
        baseRules.component = [
            { required: true, message: '请输入组件路径', trigger: 'blur' }
        ]
    }
    if (form.type !== '0') {
        baseRules.permission = [
            { required: true, message: '请输入权限标识', trigger: 'blur' }
        ]
    }
    return baseRules
})

// 获取表格数据
const getTableData = async () => {
    loading.value = true
    try {
        // TODO: 调用API获取数据
        // const res = await getMenuList()
        // tableData.value = res.data
    } catch (error) {
        console.error(error)
    } finally {
        loading.value = false
    }
}

// 展开/折叠
const handleExpandAll = () => {
    isExpandAll.value = !isExpandAll.value
    // TODO: 实现表格展开/折叠
}

// 新增
const handleAdd = (row?: any) => {
    formType.value = 'add'
    form.id = ''
    form.parentId = row?.id || ''
    form.type = row ? '1' : '0'
    form.title = ''
    form.icon = ''
    form.path = ''
    form.component = ''
    form.permission = ''
    form.sort = 0
    form.status = '1'
    dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
    formType.value = 'edit'
    Object.assign(form, row)
    dialogVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
    ElMessageBox.confirm('确认删除该菜单吗？', '提示', {
        type: 'warning'
    }).then(async () => {
        try {
            // TODO: 调用删除API
            // await deleteMenu(row.id)
            ElMessage.success('删除成功')
            getTableData()
        } catch (error) {
            console.error(error)
        }
    })
}

// 选择图标
const showIconSelect = () => {
    // TODO: 实现图标选择功能
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // TODO: 调用保存API
                // if (formType.value === 'add') {
                //     await addMenu(form)
                // } else {
                //     await updateMenu(form)
                // }
                ElMessage.success(formType.value === 'add' ? '新增成功' : '更新成功')
                dialogVisible.value = false
                getTableData()
            } catch (error) {
                console.error(error)
            }
        }
    })
}

// 初始化
getTableData()
</script>